package com.fancyy.scm;

import android.app.Application;
import android.content.SharedPreferences;

import com.fancyy.scm.bean.UserInfo;
import com.fancyy.scm.util.JsonUtil;
import com.uuzuche.lib_zxing.activity.ZXingLibrary;

/**
 * Created by any on 17/8/9.
 */

public class BRApplication extends Application {
    public static BRApplication application;
    private UserInfo userInfo;
    private String token = null;
    private Object tmpTransport;

    @Override
    public void onCreate() {
        super.onCreate();
        application = this;
        ZXingLibrary.initDisplayOpinion(this);
    }

    public <T> T getTmpTransport() {
        Object transport = tmpTransport;
        setTmpTransport(null);
        return (T)transport;
    }

    public void setTmpTransport(Object tmpTransport) {
        this.tmpTransport = tmpTransport;
    }

    public static BRApplication getInstance() {
        return application;
    }

    public void setToken(String token) {
        this.token = token;
        SharedPreferences sp = getSharedPreferences("set", MODE_PRIVATE);
        sp.edit().putString("token", token).commit();
    }

    public String getToken() {
        if (token == null) {
            SharedPreferences sp = getSharedPreferences("set", MODE_PRIVATE);
            token = sp.getString("token", null);
        }
        return token;
    }

    public UserInfo getUserInfo() {
        if (userInfo == null) {
            SharedPreferences sp = getSharedPreferences("set", MODE_PRIVATE);
            String user = sp.getString("user", null);
            if (user != null) {
                userInfo = JsonUtil.fromJson(user, UserInfo.class);
            }
        }
        return userInfo;
    }

    public void setUserInfo(UserInfo userInfo) {
        this.userInfo = userInfo;
        SharedPreferences sp = getSharedPreferences("set", MODE_PRIVATE);
        if (userInfo != null) {
            sp.edit().putString("user", JsonUtil.toJson(userInfo)).commit();
        } else {
            sp.edit().putString("user", null).commit();
        }
    }
}
